package com.aliengen.thingple.driverapp.data.local;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import com.aliengen.thingple.driverapp.network.api.exception.FieldNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
@Table(name = "Product")
public class ProductModel extends Model implements Serializable {
    @Column(name = "product_id",index = true,unique = true)
    public int product_id;

    @Column(name = "product_name")
    public String product_name;

    public ProductModel() { super(); }

    public ProductModel(JSONObject json) throws FieldNotFoundException
    {
        super();
        if (!(json.has("product_id") && json.has("product_name"))) {
            throw new FieldNotFoundException("Missing fields!");
        }

        try {
            this.product_id = json.getInt("product_id");
            this.product_name = json.getString("product_name");
        } catch(JSONException e)
        {
            throw new FieldNotFoundException(e);
        }
    }

    public static ProductModel getOrSet(JSONObject product) throws FieldNotFoundException
    {
        if(!product.has("product_id"))
        {
            throw new FieldNotFoundException("Missing product fields!");
        }

        try {
            ProductModel product_object = new Select().from(ProductModel.class).where("product_id = ?", product.getInt("product_id")).executeSingle();

            if(product_object != null)
            {
                if(product.has("product_name") && product_object.product_name.compareTo(product.getString("product_name")) != 0)
                {
                    product_object.product_name = product.getString("product_name");
                    product_object.save();
                }
                return product_object;
            }

            product_object = new ProductModel(product);
            product_object.save();

            return product_object;
        } catch(JSONException e) {
            throw new FieldNotFoundException(e.getMessage());
        }
    }

    public static ProductModel get(int product_id)
    {
        return new Select().from(ProductModel.class).where("product_id = ?", product_id).executeSingle();
    }
}
